<template>
  <div
    :ref="refName"
    :class="className"
    :style="{ height: height, width: width }"
    :optionData="optionData"
    :dark="dark"
  ></div>
</template>

<script>
import * as echarts from "echarts";

const animationDuration = 6000;

export default {
  props: {
    refName: {
      type: String,
      default: "ref",
    },
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "2000px",
    },
    height: {
      type: String,
      default: "100%",
    },
    optionData: {
      type: Object,
    },
    dark: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      lineData: null,
    };
  },
  watch: {
    optionData(newVal) {
      if (newVal && newVal.dataList && newVal.nameList) {
        this.lineData = newVal;
        this.init();
      } else {
        console.error("Invalid optionData:", newVal);
      }
    },
  },
  methods: {
    init() {
      if (
        !this.lineData ||
        !this.lineData.dataList ||
        !this.lineData.nameList
      ) {
        console.error("Invalid lineData:", this.lineData);
        return;
      }

      let dataList = this.lineData.dataList;
      let nameList = this.lineData.nameList;
      let myChart = this.dark
        ? echarts.init(this.$refs[this.refName], "dark")
        : echarts.init(this.$refs[this.refName]);
      let option = {
        dataset: [
          {
            id: "dataset_raw",
            source: dataList,
          },
        ],
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "0",
          right: "0%",
          top: "15%",
          bottom: "2%",
          containLabel: true,
        },
        xAxis: {
          show: false,
          type: "category",
        },
        yAxis: {
          type: "value",
          splitLine: { show: true },
        },
        series: [],
      };
      if (this.dark) {
        option["backgroundColor"] = "#212222";
      }
      nameList.forEach((key) => {
        let datasetItem = {
          id: key,
          fromDatasetId: "dataset_raw",
          transform: {
            type: "filter",
            config: {
              and: [
                { dimension: "time", gte: 0 },
                { dimension: "name", "=": key },
              ],
            },
          },
        };
        option.dataset.push(datasetItem);
        let seriesItem = {
          type: "line",
          datasetId: key,
          showSymbol: false,
          encode: {
            x: "time",
            y: "value",
            itemName: "name",
            tooltip: ["value"],
          },
        };
        option.series.push(seriesItem);
      });

      myChart.setOption(option);

      if (myChart) {
        myChart.resize();
      }

      myChart.on("click", function (event) {
        // 该监听器正在监听一个`echarts 事件`。
        console.log("监听一个点击事件：", event);
      });
    },
  },
};
</script>
